<template>
<div>
  <div class="crumbs">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/modelList' }">
        <i class="el-icon-lx-cascades"></i> 模型列表
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <i class="el-icon-lx-cascades"></i> 预测结果列表
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="container">
    <el-table
        :data="tableData" border class="table" ref="multipleTable"
        header-cell-class-name="table-header"
    >
      <el-table-column label="序号">
        <template #default="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间"></el-table-column>
      <el-table-column label="预测状态">
        <template #default="scope">
          <div v-if="scope.row.predictionState === 'SUCCESS'">
            预测成功
          </div>
          <div v-else-if="scope.row.predictionState === 'WAITING'">
            未预测
          </div>
          <div v-else-if="scope.row.predictionState === 'ON_GOING'">
            预测中
          </div>
          <div v-else>
            预测失败
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="finishTime" label="完成时间"></el-table-column>
      <el-table-column label="预测结果示例">
        <template #default="scope">
          <el-button type="text" class="yellow" @click="handleExample(scope.row.exampleData)">预测结果示例</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <div v-if="scope.row.predictionState === 'SUCCESS'">
            <el-button type="text" style="color: #67C23A"
                       @click="handleDownload(scope.row.predictionFileDownloadingUri)">下载
            </el-button>
            <el-button @click="handleCheckAnswer(scope.row.id)" type="text">分数审核</el-button>
          </div>
          <div v-else>
            尚未预测成功
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="downloadVisible" title="下载预测结果" width="30%">
    <el-form width="300px">
      <el-form-item label="文件名称" required>
        <el-input v-model="fileName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
          <span class="dialog-footer">
            <el-button @click="downloadVisible = false">取消</el-button>
            <el-button type="primary" @click="download" style="margin-left: 10px"> 下载 </el-button>
          </span>
    </template>
  </el-dialog>

  <el-dialog v-model="exampleVisible" title="预测结果示例" width="50%">
    <el-table
        :data="exampleArr" border class="table"
        header-cell-class-name="table-header"
    >
      <el-table-column v-for="(i,index) in exampleHead" :label="exampleHead[index]" >
        <template #default="scope">
          {{scope.row[index]}}
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
          <span class="dialog-footer">
            <el-button @click="exampleVisible = false">取消</el-button>
            <el-button type="primary" @click="exampleVisible = false" style="margin-left: 10px"> 确认 </el-button>
          </span>
    </template>
  </el-dialog>

</div>
</template>

<script>
import {getPrediction} from "../../api/prediction";
import {useRoute} from "vue-router";
import {ref} from "vue";
import {downloadFile} from "../../api/utils";
import {checkAnswer} from "../../api/introduction";
import {ElMessage, ElMessageBox} from "element-plus";

export default {
  name: "PredictionList",
  setup(){
    const route=useRoute()
    const tableData = ref([]);
    let exampleVisible =ref(false)
    let exampleHead = ref([])
    let exampleArr = ref([])

    const getPage = () => {
      const payload={
        modelId: route.query.modelId ,
        userId: localStorage.getItem("ms_userId")
      }
      getPrediction(payload).then(res => {
        if (route.query.modelId === '0') {
          tableData.value = [{
            createdTime: "模板时间",
            finishTime: "模板时间"
          }]
        }else {
          console.log( res.result)
          tableData.value=res.result;
        }
      })
    }
    getPage();
    let fileName = ref('')
    let downloadUri = ref()
    let downloadVisible = ref(false)

    const handleDownload=(url)=>{
      downloadVisible.value =true
      downloadUri.value = url
    }
    const download = () =>{
      const payload={
        fileUri: downloadUri.value
      }
      downloadFile(payload).then(data=>{
        downloadVisible.value = false
        let file = new Blob(["\ufeff" + data], { type: 'text/csv'});
        if (window.navigator.msSaveOrOpenBlob)
            // IE10+
          window.navigator.msSaveOrOpenBlob(file, fileName.value);
        else {
          // Others
          let a = document.createElement("a"),
              url = URL.createObjectURL(file);
          a.href = url;
          a.download = fileName.value;
          document.body.appendChild(a);
          a.click();
          setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
          }, 0);
        }
      })
    }
    const handleExample = (example) => {
      const arrAll = example.split('\n')
      const arrValue = []
      const reg=new RegExp("\"","g")
      exampleHead.value = ((JSON.stringify(arrAll[0])+"")
          .replace(reg,"")
          .replace("{","")
          .replace("}","")
          .replace("[","")
          .split(","))
      for (let i=1;i<arrAll.length-1;i++){
        const temp = ((JSON.stringify(arrAll[i])+"")
            .replace(reg,"")
            .replace("{","")
            .replace("}","")
            .replace("[","")
            .split(","))
        arrValue.push(temp)
      }
      arrValue.push(['...'])
      exampleArr.value = arrValue
      exampleVisible.value = true
    };

    const handleCheckAnswer=(predictionId)=>{
      console.log(predictionId)
      const payload = {
        predictionId: predictionId
      };
      checkAnswer(payload).then(res=>{
        if(res.msg === '成功') {
          ElMessageBox( {
            title: "分析结果",
            message: '你的分数是：'+res.result+' 分',
            confirmButtonText: '确定',
          });
          return res.result;
        } else{
          ElMessage.error("分数计算失败！错误码:"+res.status)
        }
      })
    }

    return {
      route,
      tableData,
      fileName,
      downloadVisible,
      exampleVisible,
      exampleHead,
      exampleArr,
      handleExample,
      getPage,
      handleDownload,
      download,
      handleCheckAnswer
    };
  },
}
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
  margin-left: 10px;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
